package com.itstyle.quartz.config;

import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.unbescape.html.HtmlEscape;

public class CustomDataSrcProcessor extends AbstractAttributeTagProcessor {

    private static final String ATTRIBUTE_NAME = "data-src";
    private static final int PRECEDENCE = 10000;
    private final String dialectPrefix;

    public CustomDataSrcProcessor(String dialectPrefix) {
        super(
                TemplateMode.HTML,
                dialectPrefix,
                null,
                false,
                ATTRIBUTE_NAME,
                true,
                PRECEDENCE,
                true
        );
        this.dialectPrefix = dialectPrefix;
    }

    @Override
    protected void doProcess(
            ITemplateContext context,
            IProcessableElementTag tag,
            AttributeName attributeName,
            String attributeValue,
            IElementTagStructureHandler structureHandler) {

        // **Thymeleaf 3.x 正确的表达式计算方式**
        final IStandardExpressionParser parser =
                StandardExpressions.getExpressionParser(context.getConfiguration());

        final IStandardExpression expression =
                parser.parseExpression(context, attributeValue);

        final String resolvedValue =
                (String) expression.execute(context);


        // 设置原生属性
        structureHandler.setAttribute("data-src", resolvedValue);
    }
}